﻿using System;
using System.Collections.Generic;
using System.Linq;
using _5E.Infrastructure.Querying;
using _5E.Infrastructure.String;
using Melee.Contract;
using Melee.DataContract.Extension;
using Melee.DataContract.Messaging;
using Melee.DataContract.Views;
using Melee.Infrastructure.Configuration;
using Melee.Models.Entity;
using Melee.Models.Repository;
using Melee.Service.Implementations;

namespace Melee.Service.Services
{
    public class UserService : IUserService
    {
        private const string LOGIN_FAILURE = "用户名或者密码不正确!";
        private IAccountRepository m_accountRepository = null;
        private IAreaRepository m_areaRepository = null;
        private ICityRepository m_cityRepository = null;
        private IPlayerRepository m_playerRepository = null;

        public UserService(
            IAccountRepository accountRepository,
            IAreaRepository areaRepository,
            ICityRepository cityRepository,
            IPlayerRepository playerRepository)
        {
            m_accountRepository = accountRepository;
            m_areaRepository = areaRepository;
            m_cityRepository = cityRepository;
            m_playerRepository = playerRepository;
        }

        public LoginResponse Login(LoginRequest request)
        {
            LoginResponse response = new LoginResponse();
            try
            {
                Query query = LoginRequestQueryGenerator.BuildQuery(request);
                IEnumerable<Account> accounts = m_accountRepository.FindBy(query);
                if (0 < accounts.Count() && accounts.First().Password.CompareByBCrypt(request.Password))
                {
                    Account account = accounts.First();
                    response.LoginId = account.Id;
                    response.UserName = m_playerRepository.FindBy(account.Id).Name;
                }
                else
                {
                    response.Success = false;
                    response.Message = LOGIN_FAILURE;
                }
            }
            catch (Exception ex)
            {
                response.Message = LOGIN_FAILURE;
                response.Exception = ex;
                response.Success = false;
            }
            return response;
        }
    }
}
